define(function(require, exports, module) {
	'use strict';
    
    var rk = require('rk');
    
    require('../../../oa/js/workreport/edit/wrEditorDialogCtrl');
    require('../../../oa/js/workreport/asset/statistics/wrStatistics_1PopupCtrl');
    require('../../../oa/js/workreport/asset/statistics/wrStatistics_2PopupCtrl');
    require('../../../oa/js/workreport/asset/statistics/wrStatistics_3PopupCtrl');
    require('../../../oa/js/workreport/asset/statistics/wrStatistics_4PopupCtrl');
    require('../../../oa/js/workreport/asset/statistics/wrStatistics_5PopupCtrl');
    require('../../../oa/js/workreport/asset/statistics/wrStatistics_6PopupCtrl');
    require('../../../oa/js/workreport/asset/statistics/wrStatistics_7PopupCtrl');
    require('../../../oa/js/workreport/asset/statistics/wrStatistics_8PopupCtrl');
    require('../../../oa/js/workreport/asset/statistics/wrStatistics_10PopupCtrl');
    require('../../../oa/js/workreport/asset/statistics/wrStatistics_11PopupCtrl');
    require('../../../oa/js/workreport/asset/statistics/wrStatistics_13PopupCtrl');
    require('../../../oa/js/workreport/asset/statistics/wrStatistics_14PopupCtrl');
    require('../../../oa/js/workreport/asset/statistics/wrStatistics_15PopupCtrl');
    require('../../../oa/js/workreport/asset/statistics/wrStatistics_CustomizedPopupCtrl');
    require('../../../oa/js/workreport/asset/statistics/wrStatisticsPopupCtrl');
    require('../../../oa/js/workreport/asset/statistics/wrStoryListCtrl');

    var rk_userService = require('core/services/2.0/rk_userService');

    (function() {
        if (!window.workreportService) window.workreportService = {};
        var workreportService = window.workreportService;
        var me = workreportService;

        var SYSTEM_ID = 601;
        me.getInitInfo = function(succ, done){
            rk.get('workreport.init', {pageNo: 1}, function (data) {
                if (data.status === 0) {
                    data = data.data;
                    //缓存信息
                    if (data.businessTypes) {
                        me.cacheBelongTypeIds(data.businessTypes);
                    }
                    if($.isFunction(succ))(succ)(data);
                }
            }).done(function(){
                if($.isFunction(done))(done)();
            });
        };
        me.getBooleanStatus = function(report) {
            report.isDraft = (report.draft == '0' ? false : true);
            report.isRead = (report.status == '2' ? true : false);
            report.isMine = false;
            if (report.updatedBy) report.isMine = (report.updatedBy == SESSION.user.id)
            if (report.createdBy) report.isMine = (report.createdBy == SESSION.user.id)
            report.canEdit = (report.isMine && report.status != '2');
            report.canDelete = report.canEdit; //已批阅2
            return report;
        };
        me.getSystemId = function() {
            return SYSTEM_ID;
        };
        var BELONGID_DAY = '25',
            BELONGID_WEEK = '26',
            BELONGID_MONTH = '27';
        // var BELONGID_DAY = '19', 
        //     BELONGID_WEEK = '20', 
        //     BELONGID_MONTH = '21';        
        var belongIdMap = [
            [BELONGID_DAY, 'day', rk.lang('WR_TITLE_DAYRPT')],
            [BELONGID_WEEK, 'week', rk.lang('WR_TITLE_WEEKRPT')],
            [BELONGID_MONTH, 'month', rk.lang('WR_TITLE_MONTHRPT')]
        ];
        var belongTypesMap = {};
        var belongTypesArr = [];
        //构造键值对
        var _typeToId = [],
            _idToType = [],
            _idToText = [],
            _typeToText = [];
        for (var i = 0; i < belongIdMap.length; i++) {
            var o = belongIdMap[i];
            var id = o[0];
            var type = o[1];
            var text = o[2];
            _typeToId[type] = id;
            _typeToText[type] = text;
            _idToType[id] = type;
            _idToText[id] = text;
        }
        me.getBelongTypes = function() {
            return belongTypesArr;
        }
        me.cacheBelongTypeIds = function(businessTypes) {
            for (var i = 0; i < businessTypes.length; i++) {
                var bt = businessTypes[i];
                if (i == 0) {
                    bt.alias = 'day';
                    bt.typeName = rk.lang('WR_TITLE_DAYRPT');
                }
                if (i == 1) {
                    bt.alias = 'week';
                    bt.typeName = rk.lang('WR_TITLE_WEEKRPT');
                }
                if (i == 2) {
                    bt.alias = 'month';
                    bt.typeName = rk.lang('WR_TITLE_MONTHRPT');
                }
                var bt = $.extend(true, {}, bt);
                belongTypesMap[bt.id + ''] = bt;
                belongTypesArr[i] = bt;
                //belongTypesArr.push(bt);
            }
        };
        me.getBelongType = function(id) {
            return belongTypesMap[id + ''];
        };
        me.getBelongTypeInfoByType = function(type) {
            for (var bid in belongTypesMap) {
                if (belongTypesMap[bid].alias == type) return belongTypesMap[bid];
            }
        };
        me.getBelongidByType = function(type) {
            //             case 'day': belongid='19'; break;
            return _typeToId[type + ''];
        };
        me.getTypeByBelongid = function(belongId) {
            //             case '19': type='day'; break;
            return _idToType[belongId + ''];
        };
        me.getBelongidText = function(belongId) {
            //             case '19': text='日报'; break;
            return _idToText[belongId + ''];
        };
        me.getBelongTextByType = function(type) {
            return _typeToText[type];
        };
        me.getDateTitle = function(startMom, type, textType) {
            startMom = rk.moment.floor(startMom); //数据有可能来自ios或android，其时间并非0点0分，因此须floor一下
            if (typeof textType == 'undefined') textType = 'default';
            if (textType == 'default') {
                switch (type) {
                    case 'day':
                        return rk.i18n('WORKREPORT_DAY_TITLE', startMom.format('YYYY-MM-DD'));
                        break;
                    case 'week':
                        var endMom = me.getEndDate(startMom, type);
                        return rk.i18n('WORKREPORT_WEEK_TITLE', startMom.format('YYYY-MM-DD'), endMom.format('YYYY-MM-DD'));
                        break;
                    case 'month':
                        var endMom = me.getEndDate(startMom, type);
                        return rk.i18n('WORKREPORT_MONTH_TITLE', startMom.format('YYYY-MM'));
                        break;
                    default:
                }
            }
            if (textType == 'cn') {
                switch (type) {
                    case 'day':
                        var format = rk.i18n('FORMAT_DATE');
                        return startMom.format(format);
                        break;
                    case 'week':
                        var format = rk.i18n('FORMAT_DATE');
                        var endMom = me.getEndDate(startMom, type);
                        return rk.i18n('WORKREPORT_WEEK_TITLE', startMom.format(format), endMom.format(format));
                        break;
                    case 'month':
                        var format = rk.i18n('FORMAT_MONTH');
                        var endMom = me.getEndDate(startMom, type);
                        return startMom.format(format);
                        break;
                    default:
                }
            }
        };
        me.getEndDate = function(startMom, type) {
            startMom = rk.moment.floor(startMom); //数据有可能来自ios或android，其时间并非0点0分，因此须floor一下
            switch (type) {
                case 'day':
                    return moment(startMom);
                    break;
                case 'week':
                    var endMom = moment(startMom);
                    endMom.add(1, 'week');
                    endMom.subtract(12, 'hours');
                    return endMom;
                    break;
                case 'month':
                    var endMom = moment(startMom);
                    endMom.add(1, 'month');
                    return endMom;
                    break;
                default:
            }
        };
        me.shouldShowStatistics = function(data) {
            return (data.businessFlg == '1');
        };
        var StatisticsInfo = me.StatisticsInfo = {
            '+number': {
                url: 'popup-activity-record-detail.action',
                title: '',
                unit: rk.i18n('WORKREPORT_UNIT_DEFAULT')
            },
            '-1': {
                url: 'popup-account-list.action',
                title: rk.i18n('WORKREPORT_ACCOUNT_LIST'),//'跟进客户',
                unit: rk.i18n('WORKREPORT_UNIT_DEFAULT')
            } //X跟进客户
            ,
            '-2': {
                url: 'popup-lead-list.action',
                title: rk.i18n('WORKREPORT_LEAD_LIST'),//'跟进线索',
                unit: rk.i18n('WORKREPORT_UNIT_LINES')
            } //X跟进线索
            ,
            '-3': {
                url: 'popup-new-account-by-type.action',
                title: rk.i18n('WORKREPORT_NEW_ACCOUNT'),//'新增客户',
                unit: rk.i18n('WORKREPORT_UNIT_DEFAULT'),
                popupWidth: 620
            } //*新增客户
            ,
            '-4': {
                url: 'popup-new-opportunity-detail.action',
                title: rk.i18n('WORKREPORT_NEW_OPP_DETAIL'),//'新增销售机会',
                unit: rk.i18n('WORKREPORT_UNIT_DEFAULT')
            } //X新增销售机会
            ,
            '-5': {
                url: 'popup-contract-amount-detail.action',
                title: rk.i18n('WORKREPORT_CONTRACT_AMOUNT_DETAIL'),//'新增合同',
                unit: rk.i18n('WORKREPORT_UNIT_DEFAULT'),
                popupWidth: 650,
                theme: 'currency'
            } //*新增合同
            ,
            '-6': {
                url: 'popup-contract-payback-detail.action',
                title: rk.i18n('WORKREPORT_PAYBACK'),//'回款',
                unit: rk.i18n('WORKREPORT_UNIT_TIMES'),
                popupWidth: 650,
                theme: 'currency'
            } //*回款
            ,
            '-7': {
                url: 'popup-opportunity-status-detail.action',
                title: rk.i18n('WORKREPORT_OPP_STATUS_DETAIL'),//'赢单金额',
                unit: rk.i18n('WORKREPORT_UNIT_DEFAULT'),
                theme: 'currency'
            } //*赢单
            ,
            '-8': {
                url: 'popup-opportunity-status-detail.action',
                title: rk.i18n('WORKREPORT_OPP_LOST'),//'输单',
                unit: rk.i18n('WORKREPORT_UNIT_DEFAULT')
            } //*输单
            ,
            '-10': {
                url: 'popup-activity-record-detail.action',
                title: rk.i18n('WORKREPORT_TASK'),//'任务',
                unit: rk.i18n('WORKREPORT_UNIT_DEFAULT')
            } //任务
            ,
            '-11': {
                url: 'popup-activity-record-detail.action',
                title: rk.i18n('WORKREPORT_RECORD'),//'记录',
                unit: rk.i18n('WORKREPORT_UNIT_DEFAULT')
            } //记录
            ,
            '-13': {
                url: 'popup-visit-record-detail.action',
                title: rk.i18n('WORKREPORT_VISIT_RECORD_TOTAL'),
                unit: rk.i18n('WORKREPORT_UNIT_DEFAULT')
            } //累计巡访记录条数
            //,
            //'-14': {
            //    url: 'popup-new-account-by-type.action?accountType=4',
            //    title: rk.i18n('WORKREPORT_NEW_AGENT'),
            //    unit: rk.i18n('WORKREPORT_UNIT_DEFAULT'),
            //    popupWidth: 620
            //} //新建代理商数
            //,
            //'-15': {
            //    url: 'popup-new-account-by-type.action?accountType=5',
            //    title: rk.i18n('WORKREPORT_NEW_TERMINAL'),
            //    unit: rk.i18n('WORKREPORT_UNIT_DEFAULT'),
            //    popupWidth: 620
            //} //新建终端数
        };
        var groupInfo;
        if (SESSION.tenantType == 1) {
            groupInfo = me.groupInfo = [{
                id: 'g1',
                title: rk.i18n('WORKREPORT_VISIT_RECORD'),//'巡访记录',
                members: ['-13']
            }, {
                id: 'g2',
                title: rk.i18n('WORKREPORT_ACT'),//'行为',
                members: ['+number', '-11', '-10', '-1', '-2']
            }];
        } else {
            groupInfo = me.groupInfo = [{
                id: 'g1',
                title: rk.i18n('WORKREPORT_PERFORMANCE'),//'业绩',
                members: ['-7', '-5', '-6', '-8']
            }, {
                id: 'g2',
                title: rk.i18n('WORKREPORT_ACT'),//'行为',
                members: ['+number', '-11', '-10', '-1', '-2']
            }, {
                id: 'g3',
                title: rk.i18n('WORKREPORT_APPEND'),//'新增',
                members: ['-3', '-4']
            }];
        }
        var groupMap = me.groupMap = {}; //将在下面的代码中生成

        //将groupInfo信息注入到StatisticsInfo中，便于生成时的遍历
        (function() {
            for (var i = 0; i < groupInfo.length; i++) {
                var group = groupInfo[i];
                var groupId = group.id;
                for (var j = 0; j < group.members.length; j++) {
                    var member = group.members[j];
                    var statisticsinfo = StatisticsInfo[member + ''];
                    statisticsinfo.groupId = groupId;
                }
                groupMap[groupId] = group;
            }
        })();

        me.updateStatisticsInfo = function(id, info) {
            var strid = id + '';
            if (!StatisticsInfo[strid]) StatisticsInfo[strid] = {};
            var currentInfo = StatisticsInfo[strid];
            for (var s in info) {
                currentInfo[s] = info[s];
            }
            if (parseInt(id) > 0) currentInfo.groupId = 'g2'; //暂时写死，视未来设计变换而动
        };
        me.setStatisticsInfo = function(info) {
            return StatisticsInfo = info;
        };
        me.getStatisticsInfo = function() {
            return StatisticsInfo;
        };
        me.getStatisticsTitle = function(id) {
            return StatisticsInfo[id] ? StatisticsInfo[id].title : rk.i18n('WORKREPORT_UNKNOWN_TYPE');
        };
        var getStatisticsQueryData = function(bizNum, startStr, endStr) {
            //var entity = $('#taskDetailDiv').wrDetailCtrl('getCurrentEntity');
            switch (bizNum) {
                case '-1':
                    return {};
                    break;
                case '-2':
                    return {};
                    break;
                case '-5':
                    return {};
                    break;
                case '-6':
                    return {};
                    break;
                case '-7':
                    return {
                        opportunityStatus: 2 //未阅|已阅
                    }
                    break;
                case '-8':
                    return {
                        opportunityStatus: 3 //未阅|已阅
                    }
                    break;
                case '-10':
                    return {
                        systemTypeId: bizNum
                    };
                    break;
                case '-11':
                    return {
                        systemTypeId: bizNum
                    };
                    break;
                default:
                    return bizNum > 0 ? {
                        systemTypeId: bizNum
                    } : {}
            }
        };
        me.popupStatistics = function(bizNum, typeAlias, belongTypeId, ownerId, start, end) {
            bizNum = parseInt(bizNum) + '';
            var bizText = StatisticsInfo[bizNum].title;
            var popupId = 'pop_statistics';
            var popup = $('#' + popupId);
            var statisticsinfo;
            if (parseInt(bizNum) > 0) {
                statisticsinfo = StatisticsInfo['+number'];
            } else {
                statisticsinfo = StatisticsInfo[bizNum + ''];
            }
            var url = '/json/oa_workreport/' + statisticsinfo.url;

            var startStr = start.unix() * 1000;
            var endStr = end.unix() * 1000;

            var queryData = getStatisticsQueryData(bizNum, startStr, endStr);
            var submitData = {
                startTime: startStr,
                endTime: endStr,
                pageUserId: ownerId,
                systemItemId: belongTypeId
            };
            submitData = $.extend(true, {}, submitData, queryData);
            var popupId = 'pop_statistics';
            var name = "myStaticPopup";

            //为统计弹出生成一个div
            $(document.body).find('#' + popupId).remove();
            $(document.body).append('<div id="' + popupId + '" class="hidden"></div>');

            $('#' + popupId).html(rk.templateText(require('oa/tmpl/workreport/asset/template_statistics-loading.tpl'), {
                bizText: bizText,
                ownerName: rk_userService.getUserInfo(ownerId).name
            }));
            rk.popup({
                name: name,
                width: (statisticsinfo.popupWidth ? statisticsinfo.popupWidth : 580),
                target: popupId,
                success: function() {
                    var winId = 'popupLayer_' + name;
                    var win = $('#' + winId);

                    bizNum = parseInt(bizNum);
                    var num = Math.abs(bizNum);

                    var ctrlName;
                    if (parseInt(bizNum) > 0) {
                        ctrlName = 'wrStatistics_CustomizedPopupCtrl';
                    } else {
                        ctrlName = 'wrStatistics_' + Math.abs(parseInt(bizNum) * -1) + 'PopupCtrl';
                    }

                    win.on('click', '.pop_close', function() {
                        $('#pop_statistics')[ctrlName]('handleClose');
                        $('#pop_statistics')[ctrlName]('destroy');
                        $.closePopupLayer()
                    });

                    $.ajax({
                        url: url,
                        data: submitData,
                        dataType: 'json',
                        type: 'GET'
                    }).success(function(data) {
                        if (!data) return;
                        if (!data.data) return;
                        //init
                        $('#pop_statistics')[ctrlName]({
                            winId: winId,
                            data: data.data,
                            bizNum: bizNum,
                            bizText: bizText,
                            ownerId: ownerId,
                            typeAlias: typeAlias,
                            start: start,
                            end: end,
                            belongTypeId: belongTypeId
                        });
                        //me.openStatisticsLayer('pop_statistics', function(){});
                    });


                }
            });
        };
        me.openStatisticsLayer = function(popupId, succFn) {
            rk.popup({
                name: "myStaticPopup",
                width: 580,
                target: popupId,
                success: function() {
                    (succFn)();
                }
            });
        };
        me.deleteReport = function(reportId, succFn) {
            rk.confirm(rk.i18n('WORKREPORT_CONFIRM_DELETE'), function() {
                var url = '/json/oa_workreport/delete.action';
                $.ajax({
                    url: url,
                    data: {
                        reportId: reportId
                    },
                    dataType: 'json',
                    type: 'POST'
                }).success(function(data) {
                    if (!data) {
                        rk.noticeError(rk.i18n('ERROR_SYSTEM_UNKNOWN'));
                        return;
                    }
                    if (data.status === 0) {
                        (succFn)();
                    } else {
                        var msg = handleStatus(data.status);
                        if (msg == 'no-such-status') {
                            rk.noticeError(rk.i18n('ERROR_DELETE_FAIL'));
                        }
                    }
                }).error(function() {
                    rk.noticeError(rk.i18n('ERROR_SYSTEM_UNKNOWN'));
                });
            });
        };
        me.sendApproval = function(act, data, succFn){
            var url;
            if(act == 'one')url = '/json/sns_work_report/marking.action';
            if(act == 'all')url = '/json/sns_work_report/markingAll.action';
            $.ajax({
                url: url,
                data: data,
                dataType: 'json',
                type:'POST'
            }).success(function(data) {
                if(!data)return;
                if(data.status !== 0)return;
                if (act == 'one') rk.noticeSuccess(rk.i18n('WORKREPORT_IS_READ'));
                if (act == 'all') rk.noticeSuccess(rk.i18n('WORKREPORT_ALL_IS_READ'));
                (succFn)();
            })
            .error(function() {})
            .complete(function() {});
    };

        var statusMap = [];
        statusMap['500'] = rk.i18n('ERROR_500');
        statusMap['314001'] = rk.i18n('ERROR_314001');
        statusMap['314002'] = rk.i18n('ERROR_314002');
        statusMap['314003'] = rk.i18n('ERROR_314003');
        statusMap['314004'] = rk.i18n('ERROR_314004');
        statusMap['100000'] = rk.i18n('ERROR_100000');
        statusMap['100001'] = rk.i18n('ERROR_100001');
        me.getErrorMsg = function(status) {
            status = status + '';
            return statusMap[status];
        }

        function handleStatus(status, noSuchCode_callback) {
            status = status + '';
            var msg = statusMap[status];
            if (msg) {
                rk.noticeError(msg);
            } else {
                if (noSuchCode_callback)(noSuchCode_callback)();
                return 'no-such-status';
            }
        };

        me.getDownloadUrl = function(reportId) {
            return '/json/oa_workreport/download.action?reportId=' + reportId;
        };

        var currencyUnit = rk.i18n('WORKREPORT_UNIT_YUAN');
        me.setCurrencyUnit = function(unit) {
            currencyUnit = unit;
        };
        me.getCurrencyUnit = function() {
            return currencyUnit;
        };


        me.popupEditor = function(info) { //for 3.0
            //require.async('oa/tmpl/workreport/asset/oa_workreport_editing.tpl',function(tpl){
            rk.dialog({
                title: (info.editorAct == 'edit' ? rk.i18n('EDIT') : rk.i18n('ADD')) + workreportService.getBelongTextByType(info.editorType),
                width: 700,
                templateId: 'oa/tmpl/workreport/tpl_workreport_editDialog.tpl',
                success: function(contentElem) {
                    contentElem.wrEditorDialogCtrl({
                        editorAct: info.editorAct,
                        reportId: info.reportId,
                        editorType: info.editorType, //day,week,month
                        belongTypeId: info.belongTypeId
                    });
                },
                footer: ['cancel', {
                        act: 'draft',
                        visible: false,
                        color: 'white',
                        text: rk.i18n('WORKREPORT_SAVE_DRAFT')
                    }, 'submit'] //弹框的按钮
            });
            //});        
        };
    })();
});
